package org.groupg.project.docvarinit;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import org.groupg.project.docvarinit.model.FileProperty;
import org.groupg.project.docvarinit.model.MainModel;
import org.groupg.project.docvarinit.services.MainServices;
import org.groupg.project.docvarinit.utils.AlertUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class HelloApplication extends Application {

    Log log = LogFactory.get();
    private final Label dirLabel1 = new Label("未选择目录");
    private final Label dirLabel2 = new Label("未选择目录");
    private final ProgressBar progressBar = new ProgressBar();
    private final Label progressLabel = new Label("进度信息");
    private final TableView<FileProperty> tableView = new TableView<>();

    private File sourceDir = null;
    private File targetDir = null;
    private final MainModel mainModel = new MainModel();


    @Override
    public void start(Stage primaryStage) {
        Button btnDir1 = new Button("选择目录1");
        Button btnDir2 = new Button("选择目录2");
        Button btnStart = new Button("开始");

        btnDir1.setOnAction(e -> {
            Platform.runLater(() -> {
                btnStart.setDisable(true);
            });
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File selectedDirectory = directoryChooser.showDialog(primaryStage);
            if (selectedDirectory != null) {
                dirLabel1.setText(selectedDirectory.getAbsolutePath());
                sourceDir = selectedDirectory;
                mainModel.setSourceDir(sourceDir);
                mainModel.setFileProperties(MainServices.getAllFilePropertyByFile(mainModel, progressBar, progressLabel));
                ObservableList<FileProperty> data = FXCollections.observableArrayList();
                data.addAll(mainModel.getFileProperties());
                Platform.runLater(() -> {
                    tableView.setItems(data);
                    btnStart.setDisable(false);
                });
                log.debug("要处理【{}】数据", tableView.getItems().size());
            }

        });

        btnDir2.setOnAction(e -> {
            DirectoryChooser directoryChooser = new DirectoryChooser();
            File selectedDirectory = directoryChooser.showDialog(primaryStage);
            if (selectedDirectory != null) {
                dirLabel2.setText(selectedDirectory.getAbsolutePath());
                targetDir = selectedDirectory;
                mainModel.setOutputDir(targetDir);
            }
        });

        btnStart.setOnAction(e -> {

            Platform.runLater(() -> {
                btnDir1.setDisable(true);
                btnDir2.setDisable(true);
            });

            if (sourceDir == null || targetDir == null) {
                AlertUtil.error("目录选择错误！", "想要点击开始，请选择两个目录");
                Platform.runLater(() -> {
                    btnDir1.setDisable(false);
                    btnDir2.setDisable(false);

                });
                return;
            }
            if (tableView.getItems().isEmpty()) {
                AlertUtil.warning("变量未解析到！", "未解析到变量，将直接复制！");
                FileUtil.del(targetDir);
                FileUtil.copy(sourceDir, targetDir, true);
                Platform.runLater(() -> {
                    btnDir1.setDisable(false);
                    btnDir2.setDisable(false);

                });
                return;
            }

            ArrayList<String> nullStrings = new ArrayList<>();
            for (int i = 0; i < tableView.getItems().size(); i++) {
                String value = tableView.getItems().get(i).propertyValueProperty().getValue();
                if (StrUtil.isEmpty(value)) {
                    int x = i + 1;
                    nullStrings.add("【" + x + "】");
                }
            }
            if (!nullStrings.isEmpty()) {
                AlertUtil.error("未完成属性编辑，无法开始程序", "想要开始，请完成第" + String.join(",", nullStrings) + "行的编辑！");
                Platform.runLater(() -> {
                    btnDir1.setDisable(false);
                    btnDir2.setDisable(false);

                });
                return;
            }

            Platform.runLater(() -> {
                // 重置进度条和标签
                progressBar.setProgress(0.0);
                progressLabel.setText("开始处理...");
            });
            mainModel.setFileProperties(tableView.getItems());
            try {
                MainServices.coverAllFiles(mainModel, progressBar, progressLabel);
            } catch (IOException ex) {
                log.error(ex.getMessage(),ex);
            }
            // 模拟进度更新
            new Thread(() -> {
                for (double i = 0; i <= 1; i += 0.1) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ex) {
                        Thread.currentThread().interrupt();
                    }
                    // 使用 Platform.runLater 来更新 UI
                    double finalI = i;
                    Platform.runLater(() -> {
                        progressBar.setProgress(finalI);
                        progressLabel.setText(String.format("进度：%.0f%%", finalI * 100));
                    });
                }
                // 最后更新
                Platform.runLater(() -> {
                    progressBar.setProgress(1.0);
                    progressLabel.setText("处理完成！");
                });
            }).start();

            Platform.runLater(() -> {
                btnDir1.setDisable(false);
                btnDir2.setDisable(false);

            });
        });

        tableView.setEditable(true);

        TableColumn<FileProperty, String> propertyNameColumn = new TableColumn<>("属性名称");
        propertyNameColumn.setMinWidth(200);
        propertyNameColumn.setCellValueFactory(cellData -> cellData.getValue().propertyNameProperty());
//        propertyNameColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        TableColumn<FileProperty, String> propertyValueColumn = new TableColumn<>("属性值");
        propertyValueColumn.setMinWidth(100);
        propertyValueColumn.setCellValueFactory(cellData -> cellData.getValue().propertyValueProperty());
        propertyValueColumn.setCellFactory(TextFieldTableCell.forTableColumn());

        tableView.getColumns().add(propertyNameColumn);
        tableView.getColumns().add(propertyValueColumn);

        // 创建两个HBox，分别包含两组目录选择控件
        HBox hBoxDir1 = new HBox(10);
        hBoxDir1.getChildren().addAll(btnDir1, dirLabel1);
        HBox.setHgrow(dirLabel1, Priority.ALWAYS); // 让标签填充剩余空间

        HBox hBoxDir2 = new HBox(10);
        hBoxDir2.getChildren().addAll(btnDir2, dirLabel2);
        HBox.setHgrow(dirLabel2, Priority.ALWAYS); // 让标签填充剩余空间

        // 创建VBox来垂直排列目录选择HBox
        VBox vBoxDirs = new VBox(10);
        vBoxDirs.getChildren().addAll(hBoxDir1, hBoxDir2);
        VBox.setVgrow(vBoxDirs, Priority.NEVER); // 不让VBox填充垂直空间

        // 创建VBox来垂直排列进度条和进度信息
        VBox vBoxProgress = new VBox(5);
        vBoxProgress.getChildren().addAll(progressLabel, progressBar);
        VBox.setVgrow(progressBar, Priority.NEVER); // 不让进度条填充垂直空间
        VBox.setVgrow(progressLabel, Priority.NEVER); // 不让进度标签填充垂直空间
        vBoxProgress.setAlignment(Pos.CENTER); // 居中显示

        // 创建开始按钮的VBox，用于垂直居中
        VBox vBoxStart = new VBox();
        vBoxStart.getChildren().add(btnStart);
        vBoxStart.setAlignment(Pos.CENTER_RIGHT); // 右对齐


        // 创建一个HBox来水平排列左侧目录选择、中间进度显示和右侧开始按钮
        HBox hBoxRoot = new HBox(10);
        HBox.setHgrow(vBoxDirs, Priority.ALWAYS); // 让目录选择填充水平空间
        HBox.setHgrow(vBoxProgress, Priority.ALWAYS); // 让进度显示填充水平空间
        hBoxRoot.getChildren().addAll(vBoxDirs, vBoxProgress, vBoxStart);

        // 创建根VBox，并添加子组件
        VBox vBoxRoot = new VBox(10);
        vBoxRoot.getChildren().addAll(hBoxRoot, tableView);
        vBoxRoot.setPadding(new Insets(10)); // 设置内边距

        // 设置场景、舞台并显示
        Scene scene = new Scene(vBoxRoot, 800, 600);
        primaryStage.setTitle("DocVarInit 文件变量处理工具 ~ Document Variable Initialization");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}